package com.aaa.system.service.imp;

import com.aaa.entity.Notice;
import com.aaa.entity.User;
import com.aaa.system.mapper.NoticeMapper;
import com.aaa.system.mapper.UserMapper;
import com.aaa.system.service.NoticeService;
import com.aaa.system.service.UserService;
import com.aaa.utils.TokenUtils;
import com.aaa.utils.WebUtil;
import com.aaa.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Objects;

@Service
public class NoticeServiceImp implements NoticeService {

    @Resource
    private NoticeMapper noticeMapper;

    @Resource
    private UserMapper userMapper;

    @Override
    public Result<IPage<Notice>> getAllList(Long current, Long size, Notice notice) {
        IPage<Notice> page = new Page<>(current,size);
        QueryWrapper<Notice> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(notice.getNoticeTitle())){
            wrapper.like("notice_title",notice.getNoticeTitle());
        }
        if (StringUtils.isNotBlank(notice.getCreateBy())){
            wrapper.like("create_by",notice.getCreateBy());
        }
        if (Objects.nonNull(notice.getStatus())){
            wrapper.eq("status",notice.getStatus());
        }
        if (Objects.nonNull(notice.getNoticeType())){
            wrapper.eq("notice_type",notice.getNoticeType());
        }
        IPage<Notice> page1 = noticeMapper.selectPage(page, wrapper);
        return new Result<>(200,"查询成功",page1);
    }

    @Override
    public Result<Boolean> saveOrUpdNotice(Notice notice) {
        String token = WebUtil.getRequest().getHeader("token");
        String username = TokenUtils.getInfo(token).get("username").toString();
        //根据手机号进行查询
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("phone",username);
        queryWrapper.eq("status",0);
        queryWrapper.eq("del_flag",0);
        User userdata = userMapper.selectOne(queryWrapper);

        if (Objects.nonNull(notice.getNoticeId())){
            //修改
            notice.setUpdateTime(LocalDateTime.now());
            notice.setUpdateBy(userdata.getUserName());
            int i = noticeMapper.updateById(notice);
            return new Result<>(200,"修改成功",i>0?true:false);
        }
        notice.setCreateTime(LocalDateTime.now());
        notice.setCreateBy(userdata.getUserName());
        int i = noticeMapper.insert(notice);
        return new Result<>(200,"添加成功",i>0?true:false);
    }

    @Override
    public Result<Boolean> delNotice(Long[] noticeIds) {
        int i = noticeMapper.bachNotice(noticeIds);
        return new Result<>(200,"删除成功",i>0?true:false);
    }
}
